/**
 * create by Alec
 */
import React, { Component } from "react";
import { connect } from "react-redux";
import { bindActionCreators } from "redux";
import PropTypes from "prop-types";
import { createForm } from "rc-form";
import autobind from "autobind-decorator";
import moment from "../../utils/moment.js";
import DatePicker from "../../components/DatePicker/index";
import {
  List,
  InputItem,
  WhiteSpace,
  // DatePicker,
  Toast,
  Icon
} from "@ali/ding-ui";

// actions
import {
  confirmEntryInfo,
  confirmSuccessInfo
} from "../../actions/confirm/index.js";

// components
import Select from "../../components/Select";

// utils
import {
  setRight,
  setTitle,
  alert,
  departmentsPicker
} from "../../utils/dingtalk.js";
import { validator, showMessage } from "../../utils/form";
import { get } from "../../utils/db.js";

// constant
const Item = List.Item;
const MAX_DEPARTMENTS = 100;
const DATE_FORMATE = "yyyy-MM-dd";
// 试用期  其他
const PROBATION__OTHER = "8";

//将store注入组件的props
const mapStateToProps = () => ({});
//将action与dispatch进行绑定并注入组件的props
const mapDispatchToProps = dispatch => ({
  //区分绑定到props的action与传递的props
  actions: bindActionCreators(
    {
      dispatch,
      confirmEntryInfo,
      confirmSuccessInfo
    },
    dispatch
  )
});

@connect(mapStateToProps, mapDispatchToProps)
class Profile extends Component {
  static defaultProps = {
    user: {},
    options: {}
  };

  //propTypes 验证
  static propTypes = {
    user: PropTypes.object,
    options: PropTypes.object,
    deptsId: PropTypes.array,
    deptsName: PropTypes.array,
    employeeType: PropTypes.any,
    form: PropTypes.shape({
      getFieldDecorator: PropTypes.func,
      getFieldsValue: PropTypes.func,
      getFieldValue: PropTypes.func,
      getFieldProps: PropTypes.func,
      validateFields: PropTypes.func,
      setFieldsValue: PropTypes.func
    }),
    actions: PropTypes.shape({
      dispatch: PropTypes.func.isRequired,
      confirmEntryInfo: PropTypes.func,
      confirmSuccessInfo: PropTypes.func
    })
  };
  constructor(props) {
    super(props);
    this.state = {
      isEditRegularTime: false,
      entrySuccess: false,
      deptsId: [],
      deptsName: [],
      regularTimeShow: true
    };
    setTitle({
      title: "确认入职"
    });
    setRight({
      text: "完成",
      onClick: this.handleClick
    });
  }
  componentWillReceiveProps(nextProps) {
    // 设置部门组件的默认值
    const { deptsId, deptsName, user } = nextProps;
    if (deptsId !== this.props.deptsId) {
      this.setState({
        deptsId,
        deptsName,
        mainDeptId: user.mainDeptId ? user.mainDeptId : deptsId[0],
        deptMapList: user.deptMapList.sort((a, b) => a.deptId - b.deptId) || []
      });
    }
  }
  componentWillUpdate() {
    setTitle({
      title: "确认入职"
    });
  }

  /**
       * 点完成提交数据
       */
  @autobind
  handleClick() {
    window._rlog(`_confirm_complete`);
    this.props.form.validateFields(err => {
      if (err) {
        showMessage(err);
      } else {
        let form = this.props.form.getFieldsValue();
        const userId = get("userId");
        const { deptsId, deptMapList = [] } = this.state;
        const { user, options } = this.props;
        // 如果dept就选了一个，那么给主部门一个默认的值
        if (deptsId.length === 1) {
          form.mainDeptId = deptsId[0];
        }
        const filterDeptName = deptMapList.filter(val => {
          return val.deptId === form.mainDeptId;
        });
        this.props.actions
          .confirmEntryInfo({
            ...form,
            userId: userId,
            dept: deptsId.join("|"),
            mainDeptName: filterDeptName.deptName
          })
          .then(res => {
            if (res.success) {
              // 隐藏右上角完成
              setRight({
                show: false
              });
              Toast.success("提交成功", 1, () => {
                window.location.hash = "/confirmed";
                // openLink('#/confirmed');
              });
            }
          });
      }
    });
  }
  /**
         * 调用钉钉手机版部门组件
         */
  @autobind
  handleDept() {
    // const corpId = getUrlParam("corpId");
    const corpId = get("corpId");
    const { deptsId } = this.state;
    const { user } = this.props;
    departmentsPicker({
      multiple: true, // 多选
      pickedDepartments: deptsId || [], // 已选部门
      maxDepartments: MAX_DEPARTMENTS, // 最大部门数
      corpId,
      cb: result => {
        let dept = [];
        let mainDeptId;
        let { departments } = result;
        departments.sort((a, b) => a.id - b.id);
        departments.forEach(val => {
          dept.push({ deptId: val.id, deptName: val.name });
        });
        const deptsId = departments.map(val => val.id);
        if (deptsId.some(val => val === user.mainDeptId)) {
          mainDeptId = user.mainDeptId;
        } else {
          mainDeptId = deptsId[0];
        }
        this.setState({
          deptsId,
          deptsName: departments.map(val => val.name),
          deptMapList: dept,
          mainDeptId
        });
        this.props.form.setFieldsValue({ mainDeptId: mainDeptId });
      },
      errCb: err => alert({ title: "出错了", message: JSON.stringify(err) })
    });
  }
  /**
       * 
       * @param {*试用期选择-转正时间联动} probationPeriod 
       */
  @autobind
  setRegularTime(probationPeriod) {
    if (probationPeriod === PROBATION__OTHER) {
      this.setState({
        isEditRegularTime: true
      });
    } else {
      const confrimJoinTime = this.props.form.getFieldValue("confrimJoinTime");
      if (confrimJoinTime) {
        const joinTime = this.props.form.getFieldValue("confrimJoinTime");
        //  .format(DATE_FORMATE);
        const regular_time = moment(joinTime).add(probationPeriod - 1, "month");

        this.props.form.setFieldsValue({
          regularTime: regular_time.format("yyyy-MM-dd")
        });
      }
      this.setState({
        isEditRegularTime: false
      });
    }
  }
  /**
     * 用户修改入职日期时，转正日期联动
     * @param date moment
     * @param dateString 如2017-07-27
     */
  @autobind
  changeConfrimJoinTime(confirmTime) {
    const probationPeriod = this.props.form.getFieldValue(
      "probationPeriodType"
    );
    const regular_time = moment(confirmTime, DATE_FORMATE).add(
      probationPeriod - 1,
      "month"
    );
    if (probationPeriod && probationPeriod !== PROBATION__OTHER) {
      this.setState({
        isEditRegularTime: false
      });
      this.props.form.setFieldsValue({
        regularTime: moment(regular_time).format("yyyy-MM-dd")
      });
    }
  }
  /**
     * 员工类型为兼职时试用期隐藏
     */
  @autobind
  changeEmployeeType(type) {
    if (type === "2" || type === "3") {
      this.setState({ regularTimeShow: false });
    } else {
      this.setState({ regularTimeShow: true });
    }
  }

  render() {
    const { getFieldDecorator } = this.props.form;
    const { user, options, employeeType } = this.props;
    const {
      deptsName = [],
      deptMapList = [],
      deptsId,
      mainDeptId,
      regularTimeShow
    } = this.state;
    const deptsNameStr = deptsName.join(",");
    const today = new Date().format("yyyy-MM-dd");
    let deptList = [];

    deptMapList.forEach(val => {
      deptList.push({ value: val.deptId, label: val.deptName });
    });

    let probationPeriod = [];
    if (this.props.form.getFieldValue("employeeStatus") === "2") {
      probationPeriod = options.probationPeriodType.slice(1);
    } else {
      probationPeriod = options.probationPeriodType;
    }
    return (
      <div className="confirm-con">
        <List className="confirm-profile">
          {!window.dd.android ? <WhiteSpace size="lg" /> : null}

          {getFieldDecorator("name", {
            initialValue: user.name,
            rules: [
              {
                label: "姓名",
                validator,
                required: true
              }
            ]
          })(
            <InputItem clear className="input-name">
              <span className="confirm-must">*</span>姓名
            </InputItem>
          )}

          {getFieldDecorator("employeeType", {
            initialValue: employeeType,
            rules: [
              {
                label: "员工类型",
                validator,
                required: true
              }
            ]
          })(
            <Select
              key="employeeType"
              options={options.employeeType}
              onChange={this.changeEmployeeType}
            >
              <span className="confirm-must">*</span>
              员工类型
            </Select>
          )}

          {getFieldDecorator("employeeStatus", {
            initialValue: "",
            rules: [
              {
                label: "员工状态",
                validator,
                required: true
              }
            ]
          })(
            <Select
              key="employeeStatus"
              options={[
                { value: "2", label: "试用" },
                { value: "3", label: "正式" }
              ]}
            >
              <span className="confirm-must">*</span>
              员工状态
            </Select>
          )}

          <WhiteSpace size="lg" />

          {getFieldDecorator("confrimJoinTime", {
            initialValue: user.preEntryTime || today
          })(
            <DatePicker
              label="入职时间"
              onChange={this.changeConfrimJoinTime}
              required
            />
          )}

          {regularTimeShow ? (
            <div>
              {getFieldDecorator("probationPeriodType")(
                <Select
                  key="probationPeriodType"
                  options={probationPeriod}
                  onChange={this.setRegularTime}
                >
                  <span className="confirm-must" />
                  试用期
                </Select>
              )}
              {getFieldDecorator("regularTime")(<DatePicker label="转正时间" />)}
            </div>
          ) : null}
          <div className="regular-time-alert">
            员工会在转正日期前15天收到提醒推送
            </div>

          <div className="dept-input-container">
            {getFieldDecorator("dept", {
              initialValue: deptsNameStr
            })(
              <InputItem
                editable={false}
                placeholder="请选择部门"
                onClick={this.handleDept}
                id="dept-input"
              >
                <span className="confirm-must">*</span>
                部门
              </InputItem>
            )}
            <Icon type="right" size="lg" className="dept-arrow-ico" />
          </div>

          {this.props.form.getFieldValue("dept").split(",").length > 1 &&
            getFieldDecorator("mainDeptId", {
              initialValue: mainDeptId || deptsId[0]
            })(
              <Select options={deptList}>
                <span className="confirm-must" />
                主部门
              </Select>
            )}

          {getFieldDecorator("position", {
            initialValue: user.position
          })(
            <InputItem clear placeholder="请输入职位">
              <span className="confirm-must" />
              职位
            </InputItem>
          )}

          {getFieldDecorator("jobnumber", {
            initialValue: user.jobnumber
          })(
            <InputItem clear placeholder="请输入工号">
              <span className="confirm-must" />
              工号
            </InputItem>
          )}

          {user.empJobNumber && (
            <div className="job-number">
              上一名加入公司的员工为{user.empJobNumber}({user.lastEmpName})
            </div>
          )}
          {getFieldDecorator("contractCompanyName", {
            initialValue: user.contractCompanyName
          })(
            <InputItem clear placeholder="请输入合同公司">
              <span className="confirm-must" />
              合同公司
            </InputItem>
          )}
          {getFieldDecorator("positionLevel", {
            initialValue: user.positionLevel
          })(
            <InputItem clear placeholder="请输入岗位职级">
              <span className="confirm-must" />
              岗位职级
            </InputItem>
          )}

          {getFieldDecorator("workPlace", {
            initialValue: user.workPlace
          })(
            <InputItem clear placeholder="请输入办公地点">
              <span className="confirm-must" />
              办公地点
            </InputItem>
          )}

          <WhiteSpace size="lg" />
          <WhiteSpace size="lg" />
          <WhiteSpace size="lg" />
        </List>
      </div>
    );
  }
}
export default createForm()(Profile);
